package com.approval.approval;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.format.DateFormat;
import android.util.Base64;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.approval.approvalapp.MainActivity;
import com.approval.approvalapp.MyAppliaction;
import com.approval.approvalapp.R;
import com.approval.approvalapp.bean.ErrorBean;
import com.approval.approvalapp.bean.UserSessionBean;
import com.approval.approvalapp.login.LoginActivity;
import com.approval.approvalapp.util.DensityUtil;
import com.approval.approvalapp.util.ErrorBeanUtil;
import com.approval.approvalapp.util.SpUtil;
import com.approval.approvalapp.util.ToastUtil;
import com.approval.approvalapp.util.base.BaseActivity;
import com.approval.approvalapp.util.net.NetRequsetUtil;
import com.approval.approvalapp.util.net.interfacepac.NetDownResponse;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Calendar;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SldlActivity extends BaseActivity implements SurfaceHolder.Callback {


    @Bind(R.id.back_iv)
    ImageView backIv;
    @Bind(R.id.tv)
    TextView tv;
    @Bind(R.id.bgiv)
    ImageView bgiv;
    private String picPath;
    private Uri imageuri;
    private final int CAMERA = 55;
    private ImageView back_iv;
    private TextView titleTv1;
    private Button btn;
    private LinearLayout root;
    private Camera mCamera;
    private ResizeAbleSurfaceView mPreview;
    private SurfaceHolder mHolder;
    private Camera.PictureCallback mPictureCallBack
             = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {

            Log.d("SldlActivityss", "1");

            Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length);


            String name = new DateFormat().format("yyyyMMddHHmmss",
                            Calendar.getInstance(Locale.CHINA)) + ".jpg";

            try {
                releaseCamera();

                if (mCamera == null) {
                    mCamera = getCamera();
                    if (mHolder != null) {
                        setStartPreview(mCamera, mHolder);
                    }
                }

                Log.d("SldlActivityss", "2");


                String base64 = bitmapToBase64(bitmap);

                    try {
                        FileWriter fw = new FileWriter(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/be64.txt");//SD卡中的路径
                        fw.flush();
                        fw.write(base64);
                        fw.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("image" , base64);

                Log.d("SldlActivityss", "4");

                NetRequsetUtil.getInstance().netRequestPostJson(
                        "v1/user/face_login"
                        , jsonObject.toString(), new NetDownResponse() {
                            @Override
                            public void success(String str) {
                                if (progressDialog == null){
                                    return;
                                }
                                UserSessionBean userSessionBean = JSON.parseObject(str, UserSessionBean.class);
                                SpUtil.saveString(SldlActivity.this, SpUtil.USER_RUN_ID, userSessionBean.getUserid());
                                SpUtil.saveString(SldlActivity.this, SpUtil.USER_RUN_NICKNAME, userSessionBean.getName());
                                SpUtil.saveString(SldlActivity.this, SpUtil.UNIT_NAME, userSessionBean.getUnit_name());
                                SpUtil.saveString(SldlActivity.this, SpUtil.REGION_CODE, userSessionBean.getRegion_code());
                                Log.d("LoginActivityss", userSessionBean.getRegion_code());
                                Log.d("LoginActivityss", userSessionBean.getOrg_code());
                                Log.d("LoginActivityss", userSessionBean.getUserid());
                                Log.d("LoginActivityss", userSessionBean.getF_userid());
                                SpUtil.saveString(SldlActivity.this, SpUtil.ORG_CODE, userSessionBean.getOrg_code());
                                SpUtil.saveString(SldlActivity.this, SpUtil.USER_NAME, userSessionBean.getUsername());
                                SpUtil.saveString(SldlActivity.this, SpUtil.F_userid, userSessionBean.getF_userid());
                                SpUtil.saveString(SldlActivity.this, SpUtil.F_orgcode, userSessionBean.getF_orgcode());
                                SpUtil.saveString(SldlActivity.this, SpUtil.F_orgname, userSessionBean.getF_orgname());
                                SpUtil.saveString(SldlActivity.this, SpUtil.Usertype, userSessionBean.getUsertype());
                                SpUtil.saveString(SldlActivity.this, SpUtil.SJLD, userSessionBean.getSJLD());
                                SpUtil.saveString(SldlActivity.this, SpUtil.SJLDN, userSessionBean.getSJLDN());
                                SpUtil.saveString(SldlActivity.this, SpUtil.GZFW1, userSessionBean.getGZFW1());
                                SpUtil.saveString(SldlActivity.this, SpUtil.GH, userSessionBean.getGh());
                                SpUtil.saveString(SldlActivity.this, SpUtil.orgename, userSessionBean.getOrgename());
                                Intent intent = new Intent(SldlActivity.this, MainActivity.class);
                                startActivity(intent);
                                LoginActivity.instance.finish();
                                SldlActivity.this.finish();
                            }

                            @Override
                            public void errowithresponse(String str) {
                                if (progressDialog == null){
                                    return;
                                }

                                progressDialog.dismiss();

                                try {
                                    ErrorBean errorBean = JSONObject.parseObject(str, ErrorBean.class);
                                    showmyDialog("", errorBean.getError_message(), "退出",
                                            "重试", new DialogClickListener() {
                                                @Override
                                                public void negativeClick() {
                                                    SldlActivity.this.finish();
                                                }

                                                @Override
                                                public void positiveClick() {
                                                    tv.postDelayed(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            if (instance == null){
                                                                return;
                                                            }
                                                            progressDialog = new ProgressDialog(SldlActivity.this);
                                                            progressDialog.setMessage("正在上传识别头像");
                                                            progressDialog.setCancelable(false);
                                                            progressDialog.show();

                                                            Camera.Parameters parameters =
                                                                    mCamera.getParameters();
                                                            parameters.setPictureFormat(ImageFormat
                                                                    .JPEG);
                                                            mCamera.takePicture(null,null,mPictureCallBack
                                                            );
                                                        }
                                                    } , 2000);
                                                }
                                            });
                                } catch (Exception e) {
                                    SldlActivity.this.finish();
                                    ToastUtil.showToast(MyAppliaction.getInstance(), "当前网络不可用,请检查网络连接");
                                }
                            }

                            @Override
                            public void erro() {
                                if (progressDialog == null){
                                    return;
                                }
                                ErrorBeanUtil.getErrorMessage(null);

                            }

                            @Override
                            public void finish() {
                                if (progressDialog == null){
                                    return;
                                }
                                progressDialog.dismiss();

                            }
                        });
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    };
    private ProgressDialog progressDialog;
    private AnimationDrawable background;

    private static SldlActivity instance;


    @Override
    public int getLayoutId() {
        instance = this;
        return R.layout.activity_sldl;
    }



    @Override
    public void initView() {
        mPreview = findViewById(R.id.preview);
        mPreview.resize(DensityUtil.dip2px(this,300f),DensityUtil.dip2px(this,430f));
        back_iv = findViewById(R.id.back_iv);
        mHolder = mPreview.getHolder();
        mHolder.addCallback(this);

//        background = (AnimationDrawable) bgiv.getBackground();
//        background.start();

        tv.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (instance == null){
                    return;
                }
                progressDialog = new ProgressDialog(SldlActivity.this);
                progressDialog.setMessage("正在上传识别头像");
                progressDialog.setCancelable(false);
                progressDialog.show();

                Camera.Parameters parameters =
                        mCamera.getParameters();
                parameters.setPictureFormat(ImageFormat
                        .JPEG);
                mCamera.takePicture(null,null,mPictureCallBack
                );
            }
        } , 3000);
    }

    @Override
    public void initData() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (null != background && background.isRunning()) {
//            background.stop();
//        }
        progressDialog = null;
        instance = null;

    }

    //获取camera对象
    private Camera getCamera() {
        Camera camera;
        try {
            camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
        } catch (Exception e) {
            camera = null;
        }

        return camera;
    }

    private void setStartPreview(Camera camera, SurfaceHolder
            holder) {
        try {
            camera.setPreviewDisplay(holder);
            camera.startPreview();
            camera.setDisplayOrientation(90);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mCamera == null) {
            mCamera = getCamera();
            if (mHolder != null) {
                setStartPreview(mCamera, mHolder);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseCamera();
    }

    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        setStartPreview(mCamera, holder);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        mCamera.stopPreview();
        setStartPreview(mCamera, mHolder);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        releaseCamera();
    }


    @OnClick({R.id.back_iv, R.id.tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_iv:
                finish();
                break;
            case R.id.tv:
                progressDialog = new ProgressDialog(SldlActivity.this);
                progressDialog.setMessage("正在上传识别头像");
                progressDialog.setCancelable(false);
                progressDialog.show();

                Camera.Parameters parameters =
                        mCamera.getParameters();
                parameters.setPictureFormat(ImageFormat
                .JPEG);
                mCamera.takePicture(null,null,mPictureCallBack
                        );
                break;
        }
    }

    public String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 30, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    public static String fileToBase64(String path) {
        // decode to bitmap
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        // convert to byte array
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 10, baos);
        byte[] bytes = baos.toByteArray();
        // base64 encode
        byte[] encode = Base64.encode(bytes, Base64.DEFAULT);
        String encodeString = new String(encode);
        return encodeString;
    }



}
